<?php

namespace App\Evaluation\Actions\Post;

use App\Extensions\Actions\RowAction;
use App\Patent;
use App\PatentApply;
use App\Services\PatentService;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class PatentAcceptPost extends RowAction
{
    public $name = '已受理';

    public function handle(PatentApply $model, Request $request)
    {
        $user = Admin::user();
        if ($user['role_type'] == 1) {
            $model->status = 1;
        }
        $patent_type_id = $model['patent_type_id'];
        $patent_name = $request->get('patent_name') ?: $model['patent_name'];
        $patent_sn = PatentService::check_patent_sn($request->get('patent_sn'), $patent_type_id);
        $apply_date = $request->get('apply_date');
        if ($model['other_applicant']) {
            $applicant = $model['patent_person'] . ',' . $model['other_applicant'];
        } else {
            $applicant = $model['patent_person'];
        }
        $data = [
            'patent_apply_id' => $model['id'],
            'patent_sn'       => $patent_sn,
            'apply_date'      => $apply_date,
            'patent_name'     => $patent_name,
            'patent_type_id'  => $patent_type_id,
            'patent_person'   => $model['patent_person'],
            'applicant'       => $applicant,
            'inventor'        => $model['inventor'],
            'user_id'         => $model['user_id'],
            'department_id'   => $model['department_id'],
            'legal_status'    => '已受理',
            'status'          => 3
        ];
        $patent = Patent::query()->where('patent_sn', $patent_sn)->first();
        if ($patent) {
            return $this->response()->swal()->error('已存在相同的申请号,不能操作')->refresh();
        }
        $model->patent_name = $patent_name;
        $model->patent_sn = $patent_sn;
        $model->apply_date = $apply_date;
        $model->save();
        $model->patent()->create($data);
        return $this->response()->success('操作成功')->refresh();
    }

    public function form()
    {
        $row = $this->row;
        $this->text('patent_name', __('Patent name'))->default($row->patent_name);
        $this->date('apply_date', __('Apply date'))->required()->default($row->apply_date);
        $this->text('patent_sn', __('Patent sn'))->rules('required|regex:/^[a-zA-Z0-9X\.]+$/', [
            'regex'    => __('Patent sn') . '组成：只能为字母、数字、点',
            'required' => __('Patent sn') . '不能为空',
        ])->default($row->patent_sn);
        $this->date('apply_date', __('Apply date'))->required()->default($row->apply_date);

    }

    public function authorize($user, $model): bool
    {
        return $user['id'] == $model['agency_id'];
    }


}
